package com.ican.dao.user;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ican.common.hibernate.HibernateDao;
import com.ican.common.hibernate.Page;
import com.ican.domain.user.Role;

@Repository("roleDao")
public class RoleDao extends HibernateDao<Role, Integer> {
    
    public Role findRoleById(Integer id){
        return this.findUnique("from Role where id = ?", id);
    }
    
    public boolean roleNameIsUnique(String name){
        Long i = findUnique("select count(id) from Role where name = ?", name);
        if(i > 0){
            return false;
        }
        return true;
    }
    
    public boolean roleNameIsUnique(Integer id, String name){
        Long i = findUnique("select count(id) from Role where name = ? and id != ?", new Object[]{name,id});
        if(i > 0){
            return false;
        }
        return true;
    }
    
    public Page<Role> findAllRole(Page<Role> page, Role role){
        StringBuffer sb = new StringBuffer("from Role");
        if(role != null){
            if(role.getName() != null && role.getName().length() > 0){
                sb.append(" where name like '%" + role.getName() + "%'");
            }
        }
        return this.findPage(page, sb.toString());
    }
    
    /**
     * @param type    0:可用；1：不可用; 其他（-1）：全部
     */
    public List<Role> findAllRole(int type){
        String hql = null;
        if(type == 0){
            hql = "from Role r where r.dataStatus = 0";
        }else if(type == 1){
            hql = "from Role r where r.dataStatus = 1";
        }else{
            hql = "from Role";
        }
        return this.find(hql);
    }
    
    public void addRole(Role role){
        role.setCreateTime(new Date());
        this.save(role);
    }
    
    public void modifyRoleName(Integer id, String name){
        String hql = "update Role r set r.name = ?, r.modifyTime = ? where r.id = ?";
        this.batchExecute(hql, new Object[]{name, new Date(), id});
    }
    
    public void modifyRoleStatus(Integer roleId, byte dataStatus){
        String hql = "update Role r set r.dataStatus = ?, r.modifyTime = ? where r.id = ?";
        this.batchExecute(hql, new Object[]{dataStatus, new Date(), roleId});
    }
    
    public List<Role> findRoleByUserId(Integer userId){
        String hql = "select r from User u join u.roles r where u.id = ? and u.dataStatus = 0 and r.dataStatus = 0";
        return this.find(hql, userId);
    }
}
